var express = require('express');
var router = express.Router();
const { Transaction, Balance } = require('../DB/FJ');

// 生成唯一ID
const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
};

// 简化的交易哈希函数
const calculateTransactionHash = (transaction) => {
  const str = `${transaction.id}${transaction.from}${transaction.to}${transaction.amount}${transaction.timestamp}`;
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    const char = str.charCodeAt(i);
    hash = ((hash << 5) - hash) + char;
    hash = hash & hash; // 转换为32位整数
  }
  return Math.abs(hash).toString(16);
};

// 生成测试地址
const generateTestAddress = () => {
  return `user_${Math.random().toString(36).substr(2, 9)}`;
};

// 获取余额
router.get('/balance/:address', async (req, res) => {
  try {
    const { address } = req.params;
    let balance = await Balance.findOne({ address });
    
    // 如果地址不存在，创建新记录并设置初始余额
    if (!balance) {
      balance = new Balance({
        address,
        balance: 1000
      });
      await balance.save();
    }
    
    res.json({
      success: true,
      balance: balance.balance
    });
  } catch (error) {
    console.error('获取余额失败:', error);
    res.status(500).json({
      success: false,
      message: '获取余额失败',
      error: error.message
    });
  }
});

// 发起转账交易
router.post('/transfer', async (req, res) => {
  try {
    const { from, to, amount } = req.body;
    
    // 验证输入
    if (!from || !to || !amount || isNaN(amount) || amount <= 0) {
      return res.status(400).json({
        success: false,
        message: '请提供有效的转账信息'
      });
    }
    
    // 检查付款方余额
    let fromBalance = await Balance.findOne({ address: from });
    let toBalance = await Balance.findOne({ address: to });
    
    // 确保付款方和收款方账户存在
    if (!fromBalance) {
      fromBalance = new Balance({
        address: from,
        balance: 1000
      });
      await fromBalance.save();
    }
    
    if (!toBalance) {
      toBalance = new Balance({
        address: to,
        balance: 1000
      });
      await toBalance.save();
    }
    
    // 检查余额是否充足
    if (fromBalance.balance < amount) {
      return res.status(400).json({
        success: false,
        message: '余额不足'
      });
    }
    
    // 创建交易记录
    const newTransaction = {
      id: generateId(),
      from,
      to,
      amount: parseFloat(amount),
      timestamp: new Date().toISOString(),
      status: 'pending'
    };
    
    // 计算交易哈希
    newTransaction.hash = calculateTransactionHash(newTransaction);
    
    // 更新余额
    fromBalance.balance -= parseFloat(amount);
    toBalance.balance += parseFloat(amount);
    
    // 保存更新后的余额和交易记录
    await fromBalance.save();
    await toBalance.save();
    
    // 更新交易状态为已完成
    newTransaction.status = 'completed';
    await new Transaction(newTransaction).save();
    
    res.json({
      success: true,
      transaction: newTransaction,
      newBalance: fromBalance.balance
    });
  } catch (error) {
    console.error('转账失败:', error);
    res.status(500).json({
      success: false,
      message: '转账失败',
      error: error.message
    });
  }
});

// 获取交易历史
router.get('/transactions/:address', async (req, res) => {
  try {
    const { address } = req.params;
    
    // 查询该地址相关的所有交易（作为付款方或收款方）
    const transactions = await Transaction.find({
      $or: [
        { from: address },
        { to: address }
      ]
    }).sort({ timestamp: -1 }); // 按时间倒序
    
    res.json({
      success: true,
      transactions
    });
  } catch (error) {
    console.error('获取交易历史失败:', error);
    res.status(500).json({
      success: false,
      message: '获取交易历史失败',
      error: error.message
    });
  }
});

// 验证交易
router.get('/verify/:transactionId', async (req, res) => {
  try {
    const { transactionId } = req.params;
    
    // 查找交易记录
    const transaction = await Transaction.findOne({ id: transactionId });
    
    if (!transaction) {
      return res.status(404).json({
        success: false,
        message: '未找到交易记录'
      });
    }
    
    // 重新计算哈希值进行验证
    const reCalculatedHash = calculateTransactionHash({
      ...transaction.toObject(),
      hash: undefined
    });
    
    const isValid = reCalculatedHash === transaction.hash;
    
    res.json({
      success: true,
      isValid,
      transaction
    });
  } catch (error) {
    console.error('验证交易失败:', error);
    res.status(500).json({
      success: false,
      message: '验证交易失败',
      error: error.message
    });
  }
});

// 生成测试地址
router.get('/generate-test-address', async (req, res) => {
  try {
    const testAddress = generateTestAddress();
    res.json({
      success: true,
      address: testAddress
    });
  } catch (error) {
    console.error('生成测试地址失败:', error);
    res.status(500).json({
      success: false,
      message: '生成测试地址失败',
      error: error.message
    });
  }
});

module.exports = router;